import { Selector } from 'antd-mobile'
import { ClockCircleOutline, BillOutline } from 'antd-mobile-icons'
import styles from '../css/train.module.css'
import { useSearchParams } from 'react-router-dom'
import { useMemo, useState } from 'react'

function TicketFooter() {
  // ? 后面的查询参数
  const [sp, setSP] = useSearchParams()
  const arr = ['isDesc', 'isSpeed', 'isSeat']

  // 数据源 useState
  const [options] = useState([
    {
      label: <ClockCircleOutline />,
      description: '出发 早 → 晚',
      value: 'isDesc'
    },
    {
      label: (
        <svg
          className="icon"
          aria-hidden="true"
          style={{ fontSize: '20px' }}
        >
          <use xlinkHref="#icon-gaotie"></use>
        </svg>
      ),
      description: '只看高铁动车',
      value: 'isSpeed'
    },
    {
      label: <BillOutline />,
      description: '只看有票',
      value: 'isSeat'
    }
  ])

  // 默认选中项
  const defaultSelected = useMemo(() => {
    const temp = []

    // 循环判断哪一项应该被勾选
    arr.forEach((key) => {
      if (sp.get(key) === 'true') {
        temp.push(key)
      }
    })

    // 判断是否需要修改第一个筛选条件的文案
    if (sp.get('isDesc') === 'true') {
      options[0].description = '耗时 短 → 长'
    }

    return temp
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sp])

  const onChange = (values) => {
    if (values.includes('isDesc')) {
      // 包含了 isDesc 这个值
      options[0].description = '耗时 短 → 长'
    } else {
      // 不包含 isDesc 这个值
      options[0].description = '出发 早 → 晚'
    }

    const obj = {
      isDesc: false,
      isSpeed: false,
      isSeat: false
    }

    values.forEach((key) => {
      obj[key] = true
    })

    // setSP({...旧参数对象, ...新参数对象})
    setSP({ ...Object.fromEntries(sp), ...obj })
  }

  return (
    <div className={styles.footer}>
      <Selector
        columns={3}
        options={options}
        // 默认选中项
        defaultValue={defaultSelected}
        multiple
        onChange={onChange}
      />
    </div>
  )
}

export default TicketFooter
